package com.example.getvideotime.util;

import com.example.getvideotime.executable.FfmpegExecutableLocator;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.MultimediaInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static jdk.nashorn.internal.objects.NativeDate.getTime;

/**
 * 视频工具类
 * @author whx
 * @date 2022/2/8
 */
@Slf4j
public class VideoUtil {

    private static final String ZERO = "0";

    public static long readVideoTimeFromCommand(String filePath, String ffmpegPath) throws IOException {
        ProcessBuilder builder = new ProcessBuilder();
        List<String> commands = new ArrayList<>();
        commands.add(ffmpegPath);
        commands.add("-i");
        commands.add(filePath);
        builder.command(commands);
        builder.redirectErrorStream(true);
        Process p = builder.start();
        // 获取执行输出信息
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder outInfo = new StringBuilder();
        String line = "";
        while ((line = br.readLine()) != null) {
            outInfo.append(line);
        }
        br.close();
        // 通过正则获取时长信息
        String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
        Pattern pattern = Pattern.compile(regexDuration);
        Matcher matcher = pattern.matcher(outInfo.toString());
        if (matcher.find()) {
            return getTime(matcher.group(1));
        }
        return 0;
    }

    /**
     * 获取时间毫秒
     * @param time 格式:"00:00:10.68"
     * @return
     */
    private static long getTime(String time) {
        int min = 0;
        String[] strs = time.split(":");
        if (strs[0].compareTo(ZERO) > 0) {
            // 秒
            min += Long.parseLong(strs[0]) * 60 * 60 * 1000;
        }
        if (strs[1].compareTo(ZERO) > 0) {
            min += Long.parseLong(strs[1]) * 60 * 1000;
        }
        if (strs[2].compareTo(ZERO) > 0) {
            min += Math.round(Double.parseDouble(strs[2]) * 1000);
        }
        return min;
    }
}